/*
 * Copyright 2011-2012 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.sabayframework.mem.impl.disk;

import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;

/**
 * Data log file.
 * Supports write-ahead logging and arbitrary position reads
 * @author Alex Antonau
 */
public final class DataLogFile extends LogFile{

	private static final int BUFFER_SIZE=1000000;
	private final int number;
	private RandomAccessFile raf;

	public DataLogFile(File file, int number) throws IOException {
		super(file, BUFFER_SIZE);
		this.number = number;
	}
	
	/**
	 * if the <code>raf</code> object exists close it.
	 * 
	 * @throws IOException
	 */
	public void close() throws IOException {
		getLock().writeLock().lock();
		try{
			super.close();
			if (raf != null) raf.close();
			raf = null;
		} finally{
			getLock().writeLock().unlock();
		}
	}
	
	public void makeReadOnly() throws IOException{
		super.close();
	}

	private RandomAccessFile getRAF() throws IOException{
		if(raf == null)	raf = new RandomAccessFile(getFile(), "r");
		return raf;
	}

	public int getNumber() {
		return number;
	}

	public byte[] read(long pos, int len)	throws IOException {
		getLock().readLock().lock();
		try{
			RandomAccessFile raf = getRAF();
			byte[] buffer = new byte[len];
			synchronized (this) {
				raf.seek(pos);
				raf.readFully(buffer);
			}
			return buffer;
		} finally{
			getLock().readLock().unlock();
		}
		
	}
	
}
